import { defineStore } from 'pinia'
import { ref } from 'vue'
import axios from 'axios'

export const useDataStore = defineStore('data', () => {
  const records = ref([])
  const total = ref(0)
  const loading = ref(false)
  const error = ref(null)
  
  async function fetchData(modelName, params = {}) {
    if (!modelName) {
      throw new Error('模型名称不能为空')
    }
    
    loading.value = true
    error.value = null
    
    try {
      console.log(`开始获取${modelName}数据，参数:`, params)
      
      const queryParams = new URLSearchParams()
      for (const key in params) {
        queryParams.append(key, params[key])
      }
      
      const url = `/api/data/${modelName}?${queryParams.toString()}`
      console.log(`请求URL: ${url}`)
      
      const response = await axios.get(url)
      console.log(`${modelName} 原始响应:`, response)
      
      if (!response || !response.data) {
        console.error(`${modelName} 响应数据为空`)
        records.value = []
        total.value = 0
        return []
      }
      
      console.log(`${modelName} 数据响应:`, response.data)
      
      if (response.data.items) {
        console.log(`${modelName} 数据包含items字段:`, response.data.items)
        
        if (Array.isArray(response.data.items)) {
          console.log(`${modelName} items是数组，长度:`, response.data.items.length)
          records.value = response.data.items
          total.value = response.data.total || response.data.items.length
          return records.value
        }
        
        if (typeof response.data.items === 'object' && response.data.items !== null && response.data.items.id) {
          console.log(`${modelName} items是单个对象，转换为数组`)
          records.value = [response.data.items]
          total.value = response.data.total || 1
          return records.value
        }
      }
      
      if (Array.isArray(response.data)) {
        console.log(`${modelName} 数据是数组，长度:`, response.data.length)
        records.value = response.data
        total.value = response.data.length
        return records.value
      }
      
      if (response.data.records && Array.isArray(response.data.records)) {
        console.log(`${modelName} 数据包含records数组，长度:`, response.data.records.length)
        records.value = response.data.records
        total.value = response.data.total || response.data.records.length
        return records.value
      }
      
      if (response.data.data && Array.isArray(response.data.data)) {
        console.log(`${modelName} 数据包含data数组，长度:`, response.data.data.length)
        records.value = response.data.data
        total.value = response.data.total || response.data.data.length
        return records.value
      }
      
      if (response.data.id) {
        console.log(`${modelName} 数据是单个对象，转换为数组`)
        records.value = [response.data]
        total.value = 1
        return records.value
      }
      
      console.error(`${modelName} 无法识别的数据格式:`, response.data)
      records.value = []
      total.value = 0
      return []
    } catch (err) {
      console.error(`获取${modelName}数据失败:`, err)
      error.value = err.message
      records.value = []
      total.value = 0
      throw err
    } finally {
      loading.value = false
    }
  }
  
  async function getRecord(modelName, id) {
    if (!modelName || !id) {
      throw new Error('模型名称和记录ID不能为空')
    }
    
    loading.value = true
    error.value = null
    
    try {
      const response = await axios.get(`/api/data/${modelName}/${id}`)
      return response.data
    } catch (err) {
      console.error(`获取${modelName}记录 ${id} 失败:`, err)
      error.value = err.message
      throw err
    } finally {
      loading.value = false
    }
  }
  
  async function createRecord(modelName, data) {
    if (!modelName) {
      throw new Error('模型名称不能为空')
    }
    
    loading.value = true
    error.value = null
    
    try {
      const response = await axios.post(`/api/data/${modelName}`, data)
      return response.data
    } catch (err) {
      console.error(`创建${modelName}记录失败:`, err)
      error.value = err.message
      throw err
    } finally {
      loading.value = false
    }
  }
  
    
    
  async function updateRecord(modelName, id, data) {
    if (!modelName || !id) {
      throw new Error('模型名称和记录ID不能为空')
    }
    
    loading.value = true
    error.value = null
    
    try {
      const response = await axios.put(`/api/data/${modelName}/${id}`, data)
      console.log(response.data)
      return response.data
    } catch (err) {
      console.error(`更新${modelName}记录 ${id} 失败:`, err)
      error.value = err.message
      throw err
    } finally {
      loading.value = false
    }}
  
  async function deleteRecord(modelName, id) {
    if (!modelName || !id) {
      throw new Error('模型名称和记录ID不能为空')
    }
    
    loading.value = true
    error.value = null
    
    try {
      await axios.delete(`/api/data/${modelName}/${id}`)
      return true
    } catch (err) {
      console.error(`删除${modelName}记录 ${id} 失败:`, err)
      error.value = err.message
      throw err
    } finally {
      loading.value = false
    }
  }
  
  return {
    records,
    total,
    loading,
    error,
    fetchData,
    getRecord,
    createRecord,
    updateRecord,
    deleteRecord
  }
}) 